package com.sec.android.app.myfiles.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.update.APKDownloadManager;
import com.sec.android.app.myfiles.update.UpdateChecker;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.UiUtils;

import static com.sec.android.app.myfiles.info.AppConstants.AppUpdateBadge;

/**
 * Created by hyejung8.kim on 2017-05-23.
 */
public final class AppUpdateReceiver extends BroadcastReceiver {
    private static final String ACTION_PKG_REPLACED = "android.intent.action.PACKAGE_REPLACED";
    private static final String ACTION_UPDATE_EXIST = "com.sec.android.app.samsungapps.UPDATE_EXISTS";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            String action = intent.getAction();
            Log.d(this, "AppUpdateReceiver onReceive() - action : " + action);

            switch (action) {
                case ACTION_UPDATE_EXIST:
                    Log.d(this, "onReceive() - New version name : " + intent.getStringExtra("version"));
                    Log.d(this, "onReceive() - New version code : " + intent.getStringExtra("versionCode"));
                    PreferenceUtils.setBadgeCount(context, AppUpdateBadge.EXIST_NEW_APP_UPDATE);
                    break;
                case ACTION_PKG_REPLACED:
                    String pkgName = intent.getData().getSchemeSpecificPart();
                    Log.d(this, "AppUpdateReceiver onReceive() - pkgName : " + pkgName);

                    if (AppConstants.CLOUD_GATEWAY_PACKAGE_NAME.equals(pkgName) || AppConstants.MY_FILES_PACKAGE_NAME.equals(pkgName)) {
                        UpdateChecker updateChecker = UpdateChecker.getInstance(context.getApplicationContext());
                        boolean isCheckMyFilesOnly = !UiUtils.isCloudGatewayEnabled(context);
                        APKDownloadManager.Result updateCheckResult = updateChecker.needUpdate(isCheckMyFilesOnly);
                        if (updateCheckResult.hasUpdate()) {
                            PreferenceUtils.setBadgeCount(context, AppUpdateBadge.EXIST_NEW_APP_UPDATE);
                        } else {
                            PreferenceUtils.setBadgeCount(context, AppUpdateBadge.NO_APP_UPDATE);
                        }
                    }
                    break;
            }
        } else {
            Log.e(this, "onReceive - intent is null");
        }
    }
}
